package com.ctgu.chatapp.view

import android.annotation.TargetApi
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import java.util.*

object ActivityCollector {
    var activities: HashMap<Class<*>, AppCompatActivity>? = LinkedHashMap()

    /**
     * 添加Activity
     *
     * @param activity
     */
    fun addActivity(activity: AppCompatActivity, clz: Class<*>) {
        activities!![clz] = activity
    }

    /**
     * 判断一个Activity 是否存在
     *
     * @param clz
     * @return
     */
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
    fun <T : AppCompatActivity?> isActivityExist(clz: Class<T>): Boolean {
        val res: Boolean
        val activity: AppCompatActivity? = getActivity(clz)
        res = if (activity == null) {
            false
        } else {
            !activity.isFinishing && !activity.isDestroyed
        }
        return res
    }

    /**
     * 获得指定activity实例
     *
     * @param clazz Activity 的类对象
     * @return
     */
    fun <T : AppCompatActivity?> getActivity(clazz: Class<T>): T? {
        return activities!![clazz] as T?
    }

    /**
     * 移除activity,代替finish
     *
     * @param activity
     */
    fun removeActivity(activity: AppCompatActivity) {
        if (activities!!.containsValue(activity)) {
            activities!!.remove(activity.javaClass)
        }
    }

    /**
     * 移除所有的Activity
     */
    fun removeAllActivity() {
        if (activities != null && activities!!.size > 0) {
            val sets: Set<Map.Entry<Class<*>, AppCompatActivity>> = activities!!.entries
            for ((_, value) in sets) {
                if (!value.isFinishing) {
                    value.finish()
                }
            }
        }
        assert(activities != null)
        activities!!.clear()
    }
}